package com.xcc.dataStructures.demo07_search;

import java.util.ArrayList;
import java.util.List;

/**
 * 二分查找
 *
 * @author xiaocheng
 * @date 2020/12/9 10:19
 */
public class BinarySearch {

    public static void main(String[] args) {
        int[] arr = {1, 1, 5, 7, 7, 7, 7, 7, 9, 11, 11};
//        int index = binarySearch(arr, 0, arr.length - 1, 7);
        List<Integer> list = binarySearch2(arr, 0, arr.length - 1, 4);
        System.out.println(list);
    }

    public static List<Integer> binarySearch2(int[] arr, int left, int right, int val) {
        if (left > right) {
            return new ArrayList<>();
        }
        int mid = (left + right) / 2;
        if (val > arr[mid]) {
            return binarySearch2(arr, mid + 1, right, val);
        } else if (val < arr[mid]) {
            return binarySearch2(arr, left, mid - 1, val);
        }else {
            List<Integer> list = new ArrayList<>();
            int temp = mid - 1;
            while (left <= temp) {
                if (arr[temp] != val) {
                    break;
                }
                list.add(temp--);
            }
            list.add(mid);

            temp = mid + 1;
            while (right >= temp) {
                if (arr[temp] != val) {
                    break;
                }
                list.add(temp++);
            }
            return list;
        }
    }

    /**
     * 二分查找算法
     */
    public static int binarySearch(int[] arr, int left, int right, int val) {
        if (left > right) {
            return -1;
        }
        int mid = (left + right) / 2;
        if (val > arr[mid]) {
            return binarySearch(arr, mid + 1, right, val);
        } else if (val < arr[mid]) {
            return binarySearch(arr, left, mid - 1, val);
        } else {
            return mid;
        }
    }

}
